import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [
  {
    path: '/index',
    name: 'index',
    component: () => import('../views/Index.vue'),
    children:[ //嵌套路由( 二级路由 )
      {
        path: '/index/home',
        name: 'home',
        meta:{title :'首页'},
        component: () => import('../views/Index/Home.vue'),
      },
      {
        path: '/index/bao',
        name: 'bao',
        meta:{title :'爆爆团'},
        component: () => import('../views/Index/Bao.vue'),
      },
      {
        path: '/index/datelist',
        name: 'datelist',
        meta:{title :'订单'},
        component: () => import('../views/Index/Datelist.vue'),
      },
      {
        path: '/index/my',
        name: 'my',      
        meta:{title :'我的'}, 
        component: () => import('../views/Index/My.vue'),
      },
      {
        path:'/index',//二级重定向
        redirect:'/index/home' 
      }, 
    ]
  },
  {
    path: '/baobao',
    name: 'baobao',  
    component: () => import('../views/BaoBao.vue')
  },
  {
    path: '/date/:id',
    name: 'date',
    meta:{title :'详情页'},
    component: () => import('../views/Date.vue')
  },
  {
    path: '/mine',
    name: 'mine',
    meta:{title :'收藏'},
    component: () => import('../views/Mine.vue')
  },
  {
    path: '/sousuo',
    name: 'sousuo',
    meta:{title :'搜索'},
    component: () => import('../views/sousuo.vue')
  },
  {
    path: '/login',
    name: 'login',
    meta:{title :'登录'},
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    meta:{title :'注册'},
    component: () => import('../views/Register.vue')
  },
  {
    path: '/notfound',
    name: 'notfound',
    component: () => import('../views/NotFound.vue')
  },
  {
    path:'/',//重定向
    redirect:'/index' 
  }, 
  {
    path:'*',
    component:()=>import('../views/NotFound.vue')
  }   
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to,from,next)=>{
  //动态更新网页标题
 document.title = to.meta.title;

 var token = localStorage.getItem('token');

 if(to.path == '/date' || to.path == '/mine'){//想要跳往 订单页 或者 我的页面
   if(token ){//已经登陆
     next();
   }else{//未登录
     next('/login');
   }

 }else{//其他页面( 非订单页 或者 我的页面)
   next();//手动调用该函数
 }
})

export default router
